import { defineComponent, ref } from 'vue'
import styles from '@/views/integration/monitor/modal-handle.module.scss'
import {
  FormInst,
  NButton,
  NForm,
  NFormItem,
  NInput,
  NInputGroup,
  NInputGroupLabel,
  NModal,
  NRadio,
  NRadioGroup,
  NSelect,
  useMessage
} from 'naive-ui'
import { useRouter } from 'vue-router'
import {
  createRuleData,
  debugPartitionDefDsl,
  getHiveMetaStoreData
} from '@/service/modules/integration-monitor'
import { PartitionDef } from '@/service/modules/integration-monitor/types'

const props = {
  propModal: {
    type: Boolean,
    default: true
  }
}

const createRule = defineComponent({
  name: 'createRule',
  props,
  emits: ['closeModal', 'updateRule'],
  setup(props, { emit }) {
    const router = useRouter()

    const ruleForm = ref({
      id: '',
      ruleCollectionId: '',
      name: '',
      analyseType: '',
      ruleLevel: '',
      calculateType: '',
      fieldsName: '',
      basePartitionDef: {
        type: '',
        dsl: '',
        name: ''
      },
      checkPartitionDef: {
        type: '',
        dsl: '',
        name: ''
      },
      fixedCompareWay: '',
      fixedValue: '',
      ifSwingUsed: '',
      swingUpper: '',
      swingLower: ''
    })

    const rules = {
      id: { required: true, message: '请输入规则组名', trigger: 'blur' },
      ruleCollectionId: {
        required: true,
        message: '请输入规则组名',
        trigger: 'blur'
      },
      name: { required: true, message: '请输入规则组名', trigger: 'blur' },
      analyseType: {
        required: true,
        message: '请输入监控类型',
        trigger: 'blur'
      },
      ruleLevel: { required: true, message: '请输入规则级别', trigger: 'blur' },
      calculateType: {
        required: true,
        message: '请选择计算类型',
        trigger: 'blur'
      },
      fieldsName: {
        required: true,
        message: '请选择字段',
        trigger: 'blur'
      },
      basePartitionDef: {
        type: {
          required: true,
          message: '请输入基准分区表达式',
          trigger: 'blur'
        },
        dsl: {
          required: true,
          message: '请输入基准分区表达式',
          trigger: 'blur'
        },
        name: {
          required: true,
          message: '请输入基准分区表达式',
          trigger: 'blur'
        }
      },
      checkPartitionDef: {
        type: {
          required: true,
          message: '请输入检查分区表达式',
          trigger: 'blur'
        },
        dsl: {
          required: true,
          message: '请输入检查分区表达式',
          trigger: 'blur'
        },
        name: {
          required: true,
          message: '请输入检查分区表达式',
          trigger: 'blur'
        }
      },
      fixedCompareWay: {
        required: true,
        message: '请选择固定值类型',
        trigger: 'blur'
      },
      fixedValue: {
        required: true,
        message: '请选择固定值类型',
        trigger: 'blur'
      },
      ifSwingUsed: {
        required: true,
        message: '请输入波动率',
        trigger: 'blur'
      },
      swingUpper: {
        required: true,
        message: '请输入波动率上限',
        trigger: 'blur'
      },
      swingLower: {
        required: true,
        message: '请输入波动率下限',
        trigger: 'blur'
      }
    }

    const onCloseModal = function () {
      emit('closeModal', true)
    }

    const ruleSubmit = function (e: MouseEvent) {
      e.preventDefault()
      formRef.value?.validate((errors) => {
        if (!errors) {
          message.success('success')
          // @ts-ignore
          createRuleData(ruleForm.value)
            .then((res: any) => {
              emit('updateRule')
              emit('closeModal')
              message.success(res.msg ? res.msg : '创建成功')
            })
            .catch((err: any) => {
              message.error(err.msg ? err.msg : '接口未知错误')
            })
        } else {
          message.error('Invalid')
        }
      })
    }

    const message = useMessage()

    const formRef = ref<FormInst | null>(null)

    const calculateTypeOptions = ref([
      {
        label: 'countAll',
        value: '总行数'
      },
      {
        label: 'nvlRate',
        value: '空值率'
      },
      {
        label: 'repeatRate',
        value: '重复率'
      },
      {
        label: 'sum',
        value: '求和'
      },
      {
        label: 'avg',
        value: '均值'
      },
      {
        label: 'max',
        value: '最大值'
      },
      {
        label: 'min',
        value: '最小值'
      }
    ])

    const fieldsList = ref([])
    const partitionList = ref([])

    const getHiveMetaStore = function () {
      // @ts-ignore
      getHiveMetaStoreData(
        // @ts-ignore
        router.currentRoute.value.query.tableName,
        router.currentRoute.value.query.schemaName
      )
        .then((res: any) => {
          fieldsList.value = res.data.sd.cols
          partitionList.value = res.data.partitionKeys
          // @ts-ignore
          if (partitionList.value[0]) {
            const temp = {
              // @ts-ignore
              name: partitionList.value[0].name,
              // @ts-ignore
              dsl: partitionList.value[0].dsl,
              // @ts-ignore
              type: partitionList.value[0].type
            }
            ruleForm.value.basePartitionDef = JSON.parse(JSON.stringify(temp))
            ruleForm.value.checkPartitionDef = JSON.parse(JSON.stringify(temp))
          } else {
            ruleForm.value.basePartitionDef = {
              name: '',
              dsl: '',
              type: ''
            }
            ruleForm.value.checkPartitionDef = {
              name: '',
              dsl: '',
              type: ''
            }
          }
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
        })
    }

    getHiveMetaStore()

    const debugPartitionDef = function (params: PartitionDef) {
      debugPartitionDefDsl(params)
        .then((res: any) => {
          message.success(res.msg ? res.msg : '接口未知错误')
          emit('updateRule')
          emit('closeModal')
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
          emit('updateRule')
          emit('closeModal')
        })
    }

    const debugBasePartitionDef = function (e: MouseEvent) {
      e.preventDefault()
      // @ts-ignore
      if (!verifyPartitionDef(ruleForm.value.basePartitionDef)) {
        return false
      }
      debugPartitionDefDsl(ruleForm.value.basePartitionDef)
        .then((res: any) => {
          message.success(res.msg ? res.msg : '测试成功')
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
        })
    }

    const debugCheckPartitionDef = function (e: MouseEvent) {
      e.preventDefault()
      // @ts-ignore
      if (!verifyPartitionDef(ruleForm.value.checkPartitionDef)) {
        return false
      }
      debugPartitionDefDsl(ruleForm.value.checkPartitionDef)
        .then((res: any) => {
          message.success(res.msg ? res.msg : '测试成功')
        })
        .catch((err: any) => {
          message.error(err.msg ? err.msg : '接口未知错误')
        })
    }

    const verifyPartitionDef = function (params: PartitionDef) {
      if (!params.dsl || !params.type || !params.name) {
        message.error('请检查表达式')
        return false
      } else {
        return true
      }
    }

    return {
      ruleForm,
      router,
      rules,
      onCloseModal,
      ruleSubmit,
      message,
      formRef,
      calculateTypeOptions,
      getHiveMetaStore,
      fieldsList,
      partitionList,
      debugPartitionDef,
      debugBasePartitionDef,
      debugCheckPartitionDef,
      verifyPartitionDef
    }
  },
  render() {
    return (
      <NModal
        v-model:show={this.$props.propModal}
        preset='card'
        class={styles['modal-handle']}
        title='新建规则'
        size='huge'
        bordered={false}
        on-close={this.onCloseModal}
      >
        <NForm
          model={this.ruleForm}
          // @ts-ignore
          rules={this.rules}
          label-placement='left'
          ref={'formRef'}
          labelWidth={140}
        >
          <NFormItem label='规则名称' path='name'>
            <NInput
              v-model:value={this.ruleForm.name}
              placeholder='请输入规则名称'
            ></NInput>
          </NFormItem>
          <NFormItem label='监控类型' path='analyseType'>
            <NRadioGroup
              // @ts-ignore
              v-model:value={this.ruleForm.analyseType}
            >
              <NRadio value={'数值'} label={'数值'}></NRadio>
              <NRadio value={'对比'} label={'对比'}></NRadio>
            </NRadioGroup>
          </NFormItem>
          <NFormItem label='规则级别' path='ruleLevel'>
            <NRadioGroup
              // @ts-ignore
              v-model:value={this.ruleForm.ruleLevel}
            >
              <NRadio value={'table'} label={'表级'}></NRadio>
              <NRadio value={'fields'} label={'字段级'}></NRadio>
            </NRadioGroup>
          </NFormItem>
          <NFormItem label='计算类型' path='calculateType'>
            <NSelect
              class={styles['form-item']}
              v-model:value={this.ruleForm.calculateType}
              options={this.calculateTypeOptions}
              placeholder={'请选择计算类型'}
              clearable
            ></NSelect>
          </NFormItem>
          <NFormItem label='选择字段' path='fieldsName'>
            <NSelect
              class={styles['form-item']}
              v-model:value={this.ruleForm.fieldsName}
              options={this.fieldsList}
              valueField={'name'}
              labelField={'name'}
              placeholder={'请选择字段'}
              clearable
            ></NSelect>
          </NFormItem>
          <NFormItem label='基准分区表达式' path='basePartitionDef.dsl'>
            <NInputGroup>
              <NInputGroupLabel>
                {this.ruleForm.basePartitionDef.name}
              </NInputGroupLabel>
              <NInput
                v-model:value={this.ruleForm.basePartitionDef.dsl}
                placeholder='请输入基准分区表达式'
              ></NInput>
              <NButton
                type={'primary'}
                // @ts-ignore
                onClick={this.debugBasePartitionDef}
              >
                测试
              </NButton>
            </NInputGroup>
          </NFormItem>
          <NFormItem label='检查分区表达式' path='checkPartitionDef.dsl'>
            <NInputGroup>
              <NInputGroupLabel>
                {this.ruleForm.checkPartitionDef.name}
              </NInputGroupLabel>
              <NInput
                v-model:value={this.ruleForm.checkPartitionDef.dsl}
                placeholder='请输入检查分区表达式'
              ></NInput>
              <NButton
                type={'primary'}
                // @ts-ignore
                onClick={this.debugCheckPartitionDef}
              >
                测试
              </NButton>
            </NInputGroup>
          </NFormItem>
          <NFormItem label='固定值类型' path='fixedCompareWay'>
            <NSelect
              class={styles['form-item']}
              v-model:value={this.ruleForm.fixedCompareWay}
              options={[
                { label: '<=', value: '<=' },
                { label: '>=', value: '>=' },
                { label: '<', value: '<' },
                { label: '>', value: '>' }
              ]}
              placeholder={'请选择固定值类型'}
              clearable
            ></NSelect>
          </NFormItem>
          <NFormItem label='固定值' path='fieldsName'>
            <NInput
              v-model:value={this.ruleForm.fieldsName}
              placeholder='请输入固定值'
            ></NInput>
          </NFormItem>
          <NFormItem label='波动率上限' path='swingUpper'>
            <NInput
              v-model:value={this.ruleForm.swingUpper}
              placeholder='请输入波动率上限'
            ></NInput>
          </NFormItem>
          <NFormItem label='波动率下限' path='swingLower'>
            <NInput
              v-model:value={this.ruleForm.swingLower}
              placeholder='请输入波动率下限'
            ></NInput>
          </NFormItem>
          <NFormItem>
            <NButton onClick={this.ruleSubmit}>提交</NButton>
          </NFormItem>
        </NForm>
      </NModal>
    )
  }
})

export default createRule
